package com.dk.springmvc02.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Controller
@RequestMapping("/stu")
public class StudentController {
    /**
     * 使用servlet API向request作用域中添加属性
     */
    @GetMapping("/getTxt")
    public String getTxt(HttpServletRequest request, @RequestParam("text") String text) {
        request.setAttribute("text", text);
        return "student";
    }

    /**
     * 使用Model向request作用域中添加属性
     */
    @GetMapping("/getTxtByModel")
    public String getTxtByModel(Model model, @RequestParam("text") String text) {
        model.addAttribute("text1", text);
        return "student";
    }

    /**
     * 使用ModelAndView向request作用域中添加属性
     */
    @GetMapping("/getTxtByModelAndView")
    public ModelAndView getTxtByModelAndView(@RequestParam("text") String text) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("text",text);
        modelAndView.addObject("text1",text);
        modelAndView.setViewName("student");
        return modelAndView;
    }

    /**
     * 使用Map向request中添加属性
     */
    @GetMapping("/getTxtByMap")
    public String getTxtByMap(Map<String,String> map,@RequestParam("text") String text){
        map.put("text",text);
        return "student";
    }

    /**
     * 使用HttpSession向session中添加属性
     */
    @GetMapping("/getTxtByHttpSession")
    public String getTxtByHttpSession(HttpSession session){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateTime = simpleDateFormat.format(new Date());
        session.setAttribute("nowTime",dateTime);
        return "student";
    }

    /**
     * 使用HttpSession获取ServletContext向Application作用域中添加属性
     */
    @GetMapping("/getTxtByServletContext")
    public String getTxtByServletContext(HttpSession session){
        ServletContext servletContext = session.getServletContext();
        servletContext.setAttribute("appNum",100);
        return "student";
    }

}
